package org.wzh.three.io.piped;

import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.util.concurrent.CountDownLatch;

/**
 * @author ewanhiz
 */
public class PipeExample {

    public static void main(String[] args) {

        CountDownLatch latch = new CountDownLatch(2);

        try (final PipedOutputStream output = new PipedOutputStream(); final PipedInputStream input = new PipedInputStream(output);) {

            Thread thread1 = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        output.write("Hello world, pipe!".getBytes());
                        latch.countDown();
                        System.out.println("out end");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });

            Thread thread2 = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        int data = input.read();
                        while (data != -1) {
                            System.out.print((char) data);
                            try {
                                data = input.read();
                            } catch (IOException e) {
                                data = -1;
                            }
                        }
                        System.out.println();
                        System.out.println("in end");
                        latch.countDown();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });

            thread1.start();
            thread2.start();
            latch.await();
            System.out.println("end");
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }

    }

}
